package com.kopi.Mensa;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import android.app.Activity;
import android.os.Bundle;
import android.text.Html;
import android.util.Log;

public class MainActivity extends Activity {
	/** Called when the activity is first created. */
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.main);

		String html = Helper
				.GetHtml("http://www.mensen.at/menu/index/print/locid/28/");
		html = Helper.CleanHtml(html);

		List<String> days = GetDays(html);
		HashMap<String, List<Meal>> dic = new HashMap<String, List<Meal>>();
		for (String d : days) {
			AddMeal(dic, d);
		}	
		
		for (String key : dic.keySet()) {
			for (Meal meal : dic.get(key)) {
				Log.d("Mensa", meal.Day + " " + meal.Date + ": " + meal.Lunch + (meal.IsVeg ? "V" : "-") + "|" + (meal.IsBrain ? "B" : "-"));
			}
		}
		
		
		Log.d("Mensa", "Finished");

	}

	private List<String> GetDays(String html) {
		List<String> ret = new ArrayList<String>();

		Pattern pattern = Pattern.compile(
				"<tr class=\"(even|odd)\">(.*?)</tr>", Pattern.MULTILINE);
		Matcher m = pattern.matcher(html);
		while (m.find())
			ret.add(m.group(2));

		ret.remove(0);

		return ret;
	}

	private void AddMeal(HashMap<String, List<Meal>> dic, String d)
    {
    	Meal meal = new Meal();
    	Pattern pTD = Pattern.compile("<td.*?>(.*?)</td>");
    	Pattern pBR = Pattern.compile("(.*)<br/>(.*)");
    	Pattern pP = Pattern.compile("<p>(.*?)</p>");
        Matcher mTD = pTD.matcher(d);
        int i = 0;
        while(mTD.find())
        {
            if (i == 0)
            {
            	Matcher m = pBR.matcher(mTD.group(1));
            	if(!m.matches())
            		continue;

        		meal.Date = m.group(2);
        		meal.Day = m.group(1);
            }
            else if (i == 1)
            {
            	Matcher m = pP.matcher(mTD.group(1));
            	int ind = 0;
            	while(m.find())
                {
            		String li = m.group(1).trim();
            		if(ind == 0)
            			meal.Lunch = li + " - ";
            		else if(li != null && li != "")            			
                        meal.Lunch += li;
                    ind++;
                }
            }
            else if (i == 2)
            {
                meal.IsVeg = mTD.group().contains("vetarian");
                meal.IsBrain = mTD.group().contains("brainfood");
            }

            i++;
        }

        if(!dic.containsKey(meal.Date))
        	dic.put(meal.Date, new ArrayList<Meal>());
        
        dic.get(meal.Date).add(meal);
    }
}